package com.xing.crm.web.controller;

import com.xing.crm.utils.ImageCompression;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * @author Mr.L
 * @version V1.0
 * @date 2021年08月02日 14:14
 */
@RestController
@RequestMapping("/Test")
public class UeTestController {

	@Autowired
	ImageCompression imageSave;

	/**
	 * 上传配置：即不走config.json，模拟config.json里的内容，解决后端配置项不正确，无法上传的问题
	 * @return
	 */

	@RequestMapping(value = "/ueditor/config",method = RequestMethod.GET)
	@ResponseBody
	public String uploadConfig(String action, String noCache) {

//		注意以下：imageActionName  根据这个ActionName的名字来上传接口：比如我现在设置的上传文件接口为下面那个：multipleCarouselFiles
//		imageUrlPrefix：是【点击确认之后，加载的资源路径】所属服务器中获取资源
//		System.out.println("进入config====================");
//		System.out.println("action="+action+"   callback="+noCache);
		String s = "{\n" +
				"            \"basePath\": \"D:/\",\n" +
				"            \"imageActionName\": \"/Test/multipleCarouselFiles\",\n" +
				"                \"imageFieldName\": \"upfile\", \n" +
				"                \"imageMaxSize\": 2048000, \n" +
				"                \"imageAllowFiles\": [\".png\", \".jpg\", \".jpeg\", \".gif\", \".bmp\"], \n" +
				"                \"imageCompressEnable\": true, \n" +
				"                \"imageCompressBorder\": 1600, \n" +
				"                \"imageInsertAlign\": \"none\", \n" +
				"                \"imageUrlPrefix\": \"/static\",\n" +
				"                \"imagePathFormat\": \"/upload/\",  /* 上传视频配置 */\n }";
		return s;
	}
	/**
	 * Ueditor上传文件
	 * 这里以上传图片为例，图片上传后，imgPath将存储图片的保存路径，返回到编辑器中做展示
	 * @param file
	 * @return
	 */
	@RequestMapping(value = "/multipleCarouselFiles",method = RequestMethod.POST)
	@ResponseBody
	public String uploadImage(@RequestParam("upfile") MultipartFile file, HttpServletRequest request, HttpServletResponse response) {

		//服务协议
		String Scheme = request.getScheme();
		//服务器名称
		String ServerName = request.getServerName();
		//服务器端口
		int Port = request.getServerPort();
		String url = Scheme+"://"+ServerName+":"+Port;
		String saveFileName = null;
		Map<String, Object> results = new HashMap(0);
		//判断非空
		if (file.isEmpty()) {
			return "上传的文件不能为空";
		}
		try {
			File upload = new File(System.getProperty("user.dir") + "/upload/");
			if(!upload.exists()){
				upload.mkdirs();
			}
//			System.out.println("上传目录为/static/images/upload/中---upload url:" + upload.getAbsolutePath());
//			测试MultipartFile接口的各个方法
//			System.out.println("[文件类型ContentType] -:"+file.getContentType());
//			System.out.println("[文件组件名称Name] -:"+file.getName());
//			System.out.println("[文件原名称OriginalFileName] -:"+file.getOriginalFilename());
//			System.out.println("[文件大小] -:"+file.getSize());
//			System.out.println(this.getClass().getName()+"图片路径："+upload);

			/* 如果不存在该路径就创建 */
			String fileName = file.getOriginalFilename();
			saveFileName = System.currentTimeMillis() + new Random().nextInt(10) + fileName.substring(fileName.lastIndexOf("."));
			File dir = new File(upload + File.separator + saveFileName);
			// 文件写入
			file.transferTo(dir);
			//照片宽度自适应压缩
            saveFileName = imageSave.thumbnail(dir.getAbsolutePath(), dir.getAbsolutePath());

			//在开发测试模式时，得到的地址为：{项目根目录}/target/static/images/upload/
			//在打包成jar正式发布时，得到的地址为：{发布jar包目录}/static/images/upload/
			results.put("msg", "上传单个文件成功");
		} catch (Exception e) {
			e.printStackTrace();
			results.put("msg", "上传单个文件失败");
		}

		String result = "";
		if(!file.isEmpty()) {
			String imgPath = "/upload/" + saveFileName;
			result = "{\n" +
					"    \"state\": \"SUCCESS\",\n" +
					"    \"url\": \"" + imgPath + "\",\n" +
					"    \"title\": \"" + saveFileName + "\",\n" +
					"    \"original\": \"" + file.getOriginalFilename() + "\"\n" +
					"}";
		}
		return result;
	}

}
